use std::io::Read;
use std::time::Duration;

fn main() -> anyhow::Result<()> {
    let mut port = serialport::new("/dev/ttyUSB2", 115_200)
        .timeout(Duration::from_millis(10))
        .open()?;
    let command = "ATI\r\n".as_bytes();
    let write_size = port.write(command)?;
    println!("Write size: {}", write_size);
    let mut serial_buf = Vec::new();
    loop {
        match port.read(serial_buf.as_mut_slice()) {
            Ok(read_size) => {
                if read_size == 0 {
                    println!("Read end!");
                    break;
                }
                let response = String::from_utf8_lossy(&serial_buf[0..read_size]);
                println!("Buffer length: {}", serial_buf.len());
                println!("Read size: {}", read_size);
                println!("Response: {}", response.trim());
            }
            Err(err) => {
                println!("Read failed: {}", err);
                break;
            }
        }
    }
    Ok(())
}
